package cn.tb.ymcc.listener;

import cn.tb.ymcc.domain.CourseOrder;
import cn.tb.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQTransactionListener(
        txProducerGroup = "service-order-producer"
)
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("本地事务执行开始");
        if(o == null){
            //没有参数，直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        try {
            CourseOrder courseOrder = (CourseOrder) o;
            courseOrderService.saveOrderAndItems(courseOrder);

        } catch (Exception e) {
            e.printStackTrace();
           return RocketMQLocalTransactionState.ROLLBACK;
        }
        //保存本地事务
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 检查本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("检查本地事务");
        try {
            byte[] byteObj = (byte[]) message.getPayload();
            String messageStr = new String(byteObj, StandardCharsets.UTF_8);
            CourseOrder order = JSONObject.parseObject(messageStr, CourseOrder.class);
            CourseOrder courseOrder = courseOrderService.selectOrderByOrderNo(order.getOrderNo());
            return courseOrder == null?RocketMQLocalTransactionState.ROLLBACK:RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
